﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxGridLookup;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxUploadControl;

namespace TheheVn.AdminPage
{
    public partial class PageManager : System.Web.UI.Page
    {
        protected const string PAGE_LIST = "PageListSS";
        protected const string PAGE_SESSION = "PageSS";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[AdminLogin.SESSION_USER] == null)
            {
                Response.Redirect("AdminLogin.aspx");
            }
            if (!IsPostBack)
            {
                if(Request.QueryString["lang"]==null||Request.QueryString["lang"]!="en")
                    rblLang.Items[1].Selected = true;
                else
                {
                    rblLang.Items[0].Selected = true;
                }

                LoadPageList();
                LoadPage();
                LoadDetailData();
            }
            else
            {
                grlPageList.DataSource = Session[PAGE_LIST];
                grlPageList.DataBind();

                grlPage.DataSource = Session[PAGE_SESSION];
                grlPage.DataBind();
            }
        }

        protected void LoadPageList()
        {
            if (Request.QueryString["act"]!=null&&(Request.QueryString["act"] == "new" || Request.QueryString["act"] == "edit"))
                btSubmit.Enabled = true;
            else
            {
                btSubmit.Enabled = false;
            }

            var table = new DataTable();
            using (var ent = new Entities())
            {
                var dt = ent.HtmlDatas.Select (p => p.Type).Distinct().ToList();
                table.Columns.Add("Type");
                foreach (var d in dt)
                {
                    var dr = table.NewRow();
                    dr["Type"] = d;
                    table.Rows.Add(dr);
                }
                if (!dt.Contains("WhatWeHave.aspx"))
                {
                    table.Rows.Add(new[] {"WhatWeHave.aspx"});
                }
                if (!dt.Contains("SubWhatDoWeDo.aspx"))
                {
                    table.Rows.Add(new[] { "SubWhatDoWeDo.aspx" });
                }
                if (!dt.Contains("SubWhoWeAre.aspx"))
                {
                    table.Rows.Add(new[] { "SubWhoWeAre.aspx" });
                }
                if (!dt.Contains("SubWhoAreOurPartner.aspx"))
                {
                    table.Rows.Add(new[] { "SubWhoAreOurPartner.aspx" });
                }
                Session[PAGE_LIST] = table;
                grlPageList.DataSource = table;
                grlPageList.DataBind();
            }
            grlPageList.Text = Request.QueryString["t"] ?? "";
            
        }

        protected void LoadDetailData()
        {
            if (Request.QueryString["id"] == null)
            {
                avartaImage.ImageUrl = "";
                htmlEditor.Html = "";
                sePriority.Value = 1;
                txtHeader.Text = "";
                return;
            }
            try
            {
                int id = Convert.ToInt32(Request.QueryString["id"]);
                using (var ent = new Entities())
                {
                    var dt = ent.HtmlDatas.FirstOrDefault(p=>p.Id==id);
                    if(dt==null) return;

                    grlPage.Text = id.ToString();
                    avartaImage.ImageUrl = dt.Image;
                    sePriority.Value = dt.Priority??1;
                    txtHeader.Text = rblLang.Items[1].Selected ? dt.VnHeader : dt.EnHeader;
                    htmlEditor.Html = rblLang.Items[1].Selected ? dt.VnHtmlText : dt.EnHtmlText;
                    if (Request.QueryString["t"] != "WhatWeHave.aspx" && Request.QueryString["t"] != "SubWhoWeAre.aspx" &&
                        Request.QueryString["t"] != "SubWhatDoWeDo.aspx" && Request.QueryString["t"] != "SubWhoAreOurPartner.aspx")
                    {
                        txtPageUrl.Text = "http://"+Request.Url.ToString().Replace("http://","").Split('/')[0] + "/" +
                                          (rblLang.Items[1].Selected ? "" : "e") + Request.QueryString["t"];
                    }
                    else
                    {
                        txtPageUrl.Text = "http://" + Request.Url.ToString().Replace("http://", "").Split('/')[0] + "/" + (rblLang.Items[1].Selected ? "" : "e") + Request.QueryString["t"] + "?id=" +
                                      Request.QueryString["id"];
                    }
                    
                }
            }
            catch (Exception)
            {
            }
            
        }

        protected void LoadPage()
        {
            Session[PAGE_SESSION] = null;
            if (Request.QueryString["t"] == null)
            {
                btNew.Enabled = btDelete.Enabled = false;
                btEdit.Enabled = false;
                return;
            }

            string type = Request.QueryString["t"];

            using (var ent = new Entities())
            {
                var dt = ent.HtmlDatas.Where(p => p.Type == type).OrderBy(p=>p.Priority).ThenByDescending(p=>p.CreateDate).ToList();
                Session[PAGE_SESSION] = dt;
                if (Request.QueryString["t"] != "WhatWeHave.aspx" && Request.QueryString["t"] != "SubWhoWeAre.aspx"
                    && Request.QueryString["t"] != "SubWhatDoWeDo.aspx" && Request.QueryString["t"] != "SubWhoAreOurPartner.aspx")
                {
                    btNew.Enabled = btDelete.Enabled = false;
                    btEdit.Enabled = true;
                }
                else
                {
                    btNew.Enabled = true;
                    if (dt.Count > 0)
                        btDelete.Enabled = btEdit.Enabled = true;
                    else
                    {
                        btDelete.Enabled = btEdit.Enabled = false;
                    }
                }
                grlPage.DataSource = Session[PAGE_SESSION];
                grlPage.DataBind();
                FileUpload1.Enabled =btUpload.Enabled = sePriority.Enabled = txtHeader.Enabled = htmlEditor.Enabled = false;
                grlPage.Text = Request.QueryString["id"] ??"";
                if (Request.QueryString["act"] != null && (Request.QueryString["act"] == "new"))
                {
                    btNew.Enabled = true;
                    btEdit.Enabled = btDelete.Enabled = false;
                    FileUpload1.Enabled =btUpload.Enabled = sePriority.Enabled = txtHeader.Enabled = htmlEditor.Enabled = true;
                }
                if (Request.QueryString["act"] != null && (Request.QueryString["act"] == "edit"))
                {
                    btNew.Enabled = false;
                    btEdit.Enabled = btDelete.Enabled = true;
                    FileUpload1.Enabled =btUpload.Enabled = sePriority.Enabled = txtHeader.Enabled = htmlEditor.Enabled = true;
                }
            }
           
        }

        protected void btLogout_Click(object sender, EventArgs e)
        {
            Session[AdminLogin.SESSION_USER] = null;
            Response.Redirect("AdminLogin.aspx");
        }


        protected void grlPage_ValueChanged(object sender, EventArgs e)
        {
            var data = grlPage.GridView.GetSelectedFieldValues("Priority");
            try
            {
                sePriority.Number = Convert.ToInt32(data);
            }
            catch (Exception)
            {
            }
        }

        protected void btUpload_Click(object sender, EventArgs e)
        {
            if(!FileUpload1.HasFile) return;
            string folder = "~/NewsImage/";
            string abc = Server.MapPath(folder);
            FileUpload1.SaveAs(abc + "\\" + FileUpload1.FileName);
            string file = folder + "/" + FileUpload1.FileName;
            avartaImage.ImageUrl = file;
        }

        protected void AddNews()
        {
            var data = new HtmlData();
            data.CreateDate = DateTime.Now;
            data.Priority = Convert.ToInt32(sePriority.Number);
            data.Image = avartaImage.ImageUrl;
            data.Type = grlPageList.Text;
            if (rblLang.Items[1].Selected)
            {
                data.VnHtmlText = htmlEditor.Html;
                data.VnHeader = txtHeader.Text;
            }
            else
            {
                data.EnHtmlText = htmlEditor.Html;
                data.EnHeader = txtHeader.Text;
            }
            using (var ent = new Entities())
            {
                ent.HtmlDatas.Add(data);
                ent.SaveChanges();
            }
            string str = Request.Url.ToString().Replace("&act=new", "");
            str += "&id=" + data.Id;
            Response.Redirect(str);
        }

        protected void btNew_Click(object sender, EventArgs e)
        {
            var url = "PageManager.aspx?t=" + grlPageList.Text + "&act=new&lang=" + (rblLang.Items[1].Selected?"vn":"en");

            Response.Redirect(url);
        }

        protected void EditNews()
        {
            try
            {
                using (var ent = new Entities())
                {
                    int id = Convert.ToInt32(grlPage.Text);
                    var data = ent.HtmlDatas.FirstOrDefault(p => p.Id == id);
                    if (data == null) return;
                    data.Priority = Convert.ToInt32(sePriority.Number);
                    if (!string.IsNullOrEmpty(avartaImage.ImageUrl))
                        data.Image = avartaImage.ImageUrl;
                    if (rblLang.Items[1].Selected)
                    {
                        data.VnHtmlText = htmlEditor.Html;
                        data.VnHeader = txtHeader.Text;
                    }
                    else
                    {
                        data.EnHtmlText = htmlEditor.Html;
                        data.EnHeader = txtHeader.Text;
                    }
                    ent.SaveChanges();
                }
                string str = Request.Url.ToString().Replace("&act=edit","");
                Response.Redirect(str);
            }
            catch (Exception)
            {
            }
        }

        protected void btEdit_Click(object sender, EventArgs e)
        {
            var url = "PageManager.aspx?t=" + grlPageList.Text+"&id="+grlPage.Text + "&act=edit&lang=" + (rblLang.Items[1].Selected ? "vn" : "en");
            Response.Redirect(url);
        }

        protected void btDelete_Click(object sender, EventArgs e)
        {
            try
            {
                using (var ent = new Entities())
                {
                    int id = Convert.ToInt32(grlPage.Text);
                    var data = ent.HtmlDatas.FirstOrDefault(p => p.Id == id);
                    if (data == null) return;
                    ent.HtmlDatas.Remove(data);
                    ent.SaveChanges();
                }
                var url = "PageManager.aspx?t=" + grlPageList.Text;
                Response.Redirect(url);
            }
            catch (Exception)
            {
            }
        }

        protected void grlPageList_ValueChanged(object sender, EventArgs e)
        {
            var url="PageManager.aspx?t="+grlPageList.Text;
            if (Page.IsCallback)
                DevExpress.Web.ASPxClasses.ASPxWebControl.RedirectOnCallback(url);
            else
                Response.Redirect(url);
        }

        protected void grlPage_ValueChanged1(object sender, EventArgs e)
        {
            var url="PageManager.aspx?t=" + grlPageList.Text+"&id="+grlPage.Text+"&lang="+(rblLang.Items[1].Selected?"vn":"en");
            if (Page.IsCallback)
                DevExpress.Web.ASPxClasses.ASPxWebControl.RedirectOnCallback(url);
            else
                Response.Redirect(url);
        }

        protected void btSubmit_Click(object sender, EventArgs e)
        {
            if(Request.QueryString["act"]==null)return;
            switch (Request.QueryString["act"])
            {
                case "new":
                    AddNews();
                    break;
                case "edit":
                    EditNews();
                    break;
                    ;
            }
        }

        protected void rblLang_SelectedIndexChanged(object sender, EventArgs e)
        {
            var url = Request.Url.ToString();
            if (url.Contains("&lang=vn"))
            {
                url = rblLang.Items[1].Selected ? url : url.Replace("&lang=vn", "&lang=en");
            }
            else if (url.Contains("&lang=en"))
            {
                url = !rblLang.Items[1].Selected ? url : url.Replace("&lang=en", "&lang=vn");
            }
            else return;

             if (Page.IsCallback)
                    DevExpress.Web.ASPxClasses.ASPxWebControl.RedirectOnCallback(url);
                else
                    Response.Redirect(url);
        }

    }
}